<?php
declare (strict_types=1);

namespace app\listener\agent;

use app\event\AgentAddSuccess;
use app\model\Agent;
use app\model\Config;
use app\model\CouponConfig;

class AgentAddSuccessPremiumRate
{
    /**
     * 事件监听处理
     * @param AgentAddSuccess $event
     * @return mixed
     */
    public function handle(AgentAddSuccess $event)
    {
        /**
         * @var Agent
         */
        $agent = $event->agent;
        if (!$agent) {
            return;
        }
        /**
         * @var Config $agentPremiumRate
         */
        $agentPremiumRate = (new Config())->getAgentPremiumRate();
        if (!$agentPremiumRate) {
            return;
        }
        $coupon_config = CouponConfig::query()
            ->where('agent_id', $agent->id)
            ->where('global', CouponConfig::GLOBAL_DLQJ)
            ->where('status', CouponConfig::STATUS_ACTIVE)
            ->find();
        if ($coupon_config) {
            return;
        }
        CouponConfig::create([
            'agent_id' => $agent->id,
            'value'    => $agentPremiumRate->value,
            'status'   => CouponConfig::STATUS_ACTIVE,
            'global'   => CouponConfig::GLOBAL_DLQJ,
        ]);
    }
}
